﻿using DevExpress.XtraEditors;
using DevExpress.XtraPrinting;
using MesProjectWinform.Entity.Request;
using MesProjectWinform.Helper;
using MesProjectWinform.Public;
using MesProjectWinform.Public.Common;
using MesProjectWinform.WareHouse.Entity;
using MesProjectWinform.用户控件;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MesProjectWinform.WareHouse.Form.外部标签解析
{
    public partial class Form_TagLable : DevExpress.XtraEditors.XtraForm
    {
        // 分页控件
        private PaginationControl paginationControl;
        
        // 分页参数
        private int currentPage = 1;
        private int pageSize = 10;
        private int totalRecords = 0;
        
        public Form_TagLable()
        {
            InitializeComponent();
            
            // 初始化分页控件
            InitPaginationControl();
        }
        
        /// <summary>
        /// 初始化分页控件
        /// </summary>
        private void InitPaginationControl()
        {
            // 创建分页控件
            paginationControl = new PaginationControl();
            paginationControl.Dock = DockStyle.Fill;
            paginationControl.PageSize = pageSize;
            paginationControl.CurrentPage = currentPage;
            paginationControl.TotalRecords = totalRecords;
            
            // 设置每页记录数选项
            paginationControl.PageSizeOptions = new List<int> { 5, 10, 20, 50, 100 };
            
            // 绑定事件
            paginationControl.PageChanged += PaginationControl_PageChanged;
            paginationControl.PageSizeChanged += PaginationControl_PageSizeChanged;
            
            // 添加到panelControl3
            panelControl3.Controls.Add(paginationControl);
        }
        
        /// <summary>
        /// 页码改变事件处理
        /// </summary>
        private void PaginationControl_PageChanged(object sender, PageChangedEventArgs e)
        {
            currentPage = e.CurrentPage;
            pageSize = e.PageSize;
            LoadData();
        }
        
        /// <summary>
        /// 每页记录数改变事件处理
        /// </summary>
        private void PaginationControl_PageSizeChanged(object sender, PageSizeChangedEventArgs e)
        {
            try
            {
                // 先更新分页参数
                currentPage = e.CurrentPage;
                pageSize = e.PageSize;
                
                // 禁用控件，防止重复操作
                if (paginationControl != null)
                {
                    paginationControl.Enabled = false;
                }
                
                // 显示等待光标
                Cursor = Cursors.WaitCursor;
                
                // 使用BeginInvoke确保UI线程完成当前操作后再加载数据
                BeginInvoke(new Action(() => {
                    try
                    {
                        LoadData();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("加载数据时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        // 恢复控件状态
                        if (paginationControl != null)
                        {
                            paginationControl.Enabled = true;
                        }
                        
                        // 恢复光标
                        Cursor = Cursors.Default;
                    }
                }));
            }
            catch (Exception ex)
            {
                // 恢复控件状态
                if (paginationControl != null)
                {
                    paginationControl.Enabled = true;
                }
                
                // 恢复光标
                Cursor = Cursors.Default;
                
                MessageBox.Show("每页记录数改变处理时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form_ShowWareHouse_Load(object sender, EventArgs e)
        {
            // 加载初始数据
            LoadData();
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnQry_Click(object sender, EventArgs e)
        {
            try
            {
                // 重置为第一页
                currentPage = 1;
                if (paginationControl != null)
                {
                    paginationControl.CurrentPage = 1;
                }
                
                // 加载数据
                LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show("执行查询时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAdd_Click(object sender, EventArgs e)
        {
            Form_TagLableAdd from = new Form_TagLableAdd();
            from.UpdateType = true;
            if (from.ShowDialog() == DialogResult.OK)
            {
                Clear();
            }
        }

        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnClear_Click(object sender, EventArgs e)
        {
            try
            {
                // 清空查询条件
                TxtCode.Text = string.Empty;
                TxtName.Text = string.Empty;
                
                // 重置为第一页
                currentPage = 1;
                if (paginationControl != null)
                {
                    paginationControl.CurrentPage = 1;
                }
                
                // 加载数据
                LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show("刷新数据时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Export_Click(object sender, EventArgs e)
        {
            try
            {
                // 创建保存对话框
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.Filter = "Excel文件|*.xlsx|Excel 97-2003|*.xls";
                saveDialog.Title = "导出Excel";
                saveDialog.FileName = "外部标签解析信息_" + DateTime.Now.ToString("yyyyMMddHHmmss");
                saveDialog.RestoreDirectory = true;

                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    // 显示等待提示
                    Cursor = Cursors.WaitCursor;

                    // 根据文件扩展名选择导出格式
                    string extension = Path.GetExtension(saveDialog.FileName).ToLower();

                    if (extension == ".xlsx")
                    {
                        // 导出为XLSX格式
                        ExportToExcelAdvanced(saveDialog.FileName, true);
                    }
                    else if (extension == ".xls")
                    {
                        // 导出为XLS格式
                        ExportToExcelAdvanced(saveDialog.FileName, false);
                    }

                    // 恢复光标
                    Cursor = Cursors.Default;

                    // 询问是否打开文件
                    if (MessageBox.Show("导出成功，是否立即打开？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        System.Diagnostics.Process.Start(saveDialog.FileName);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出Excel时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void DeleteBtn_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                // 获取当前选中行的数据 - 使用两种方式尝试获取选中行
                var view = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
                if (view != null && view.SelectedRowsCount > 0)
                {
                    // 获取当前选中行的标签名称和ID
                    int rowHandle = view.GetSelectedRows()[0];
                    string labelId = view.GetRowCellValue(rowHandle, "LId").ToString();
                    string labelName = view.GetRowCellValue(rowHandle, "LabName")?.ToString() ?? "未命名标签";

                    // 显示确认对话框
                    DialogResult result = MessageBox.Show($"确定要删除标签 \"{labelName}\" 吗？\n删除后将无法恢复！",
                                                          "删除确认",
                                                          MessageBoxButtons.YesNo,
                                                          MessageBoxIcon.Warning,
                                                          MessageBoxDefaultButton.Button2);

                    // 用户确认删除
                    if (result == DialogResult.Yes)
                    {
                        // 显示正在处理的提示
                        Cursor = Cursors.WaitCursor;

                        // 调用删除API
                        string action = "WareHouse/Label/UpdateDelete?Id=" + labelId;
                        string json = await HttpClientHelper.RequestUrl(RequestType.Delete, action, null);
                        ApiResult<int> model = JsonConvert.DeserializeObject<ApiResult<int>>(json);
                        // 如果操作成功，刷新数据
                        if (model.Code == ApiEnums.Success)
                        {
                            // 重新加载数据
                            LoadData();
                        }
                        else
                        {
                            MessageBox.Show(model.Message, "操作失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        // 恢复光标
                        Cursor = Cursors.Default;
                    }
                }
                
                else
                {
                    MessageBox.Show("请先选择要删除的仓库", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show("删除操作失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Update_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                if (gridView1.FocusedRowHandle >= 0)
                {
                    // 显示等待光标
                    Cursor = Cursors.WaitCursor;

                    Form_TagLableAdd from = new Form_TagLableAdd();
                    from.UpdateType = false;

                    // 获取当前选中行的数据
                    DataRow row = gridView1.GetFocusedDataRow();

                    try
                    {
                        // 创建LableModel对象并填充数据
                        LableModel label = new LableModel();
                        label.LId = long.Parse(row["LId"].ToString());
                        label.LalId = row["LalId"].ToString();
                        label.LabName = row["LabName"].ToString();
                        label.SupplierId = row["SupplierId"]?.ToString();
                        label.SupplierName = row["SupplierName"]?.ToString();
                        label.Format = row["Format"]?.ToString();
                        label.FormatMemo = row["FormatMemo"]?.ToString();
                        label.Delimiter = row["Delimiter"]?.ToString();
                        label.Memo = row["Memo"]?.ToString();
                        label.CreatedBy = row["CreatedBy"]?.ToString();
                        label.EMPID = row["EMPID"]?.ToString();
                        label.EMPName = row["EMPName"]?.ToString();
                        label.IsEnable = Convert.ToBoolean(row["IsEnable"]);

                        // 安全地转换日期时间
                        if (row["CreatedTime"] != DBNull.Value)
                        {
                            label.CreatedTime = Convert.ToDateTime(row["CreatedTime"]);
                        }

                        if (row["UpdatedTime"] != DBNull.Value)
                        {
                            label.UpdatedTime = Convert.ToDateTime(row["UpdatedTime"]);
                        }

                        // 传递LableModel对象到编辑窗体
                        from.CurrentLabel = label;

                        // 恢复光标
                        Cursor = Cursors.Default;

                        // 显示编辑窗体
                        if (from.ShowDialog() == DialogResult.OK)
                        {
                            // 编辑成功后刷新数据
                            Clear();
                        }
                    }
                    catch (FormatException fex)
                    {
                        MessageBox.Show("数据格式错误：" + fex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show("请先选择要修改的仓库", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show("修改操作失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 确保光标恢复正常
                Cursor = Cursors.Default;
            }
        }

        #region 自定义方法
        
        /// <summary>
        /// 加载数据
        /// </summary>
        private async void LoadData()
        {
            try
            {
                // 禁用分页控件，防止重复操作
                if (paginationControl != null)
                {
                    paginationControl.Enabled = false;
                }
                
                // 显示等待光标
                Cursor = Cursors.WaitCursor;
                
                string action;
               
                // 对查询参数进行URL编码，避免特殊字符问题
                string encodedCode = Uri.EscapeDataString(TxtCode.Text.Trim());
                string encodedName = Uri.EscapeDataString(TxtName.Text.Trim());
                action = $"WareHouse/Label/GetLabel?pageNum={currentPage}&pageSize={pageSize}&QryID={encodedCode}&QryName={encodedName}";

                // 调用API
                string json = await HttpClientHelper.RequestUrl(RequestType.Get, action, null);
                ApiPaging<List<LableModel>> model = JsonConvert.DeserializeObject<ApiPaging<List<LableModel>>>(json);
                // 使用安全的UI更新方式
                UpdateUIWithData(model);
            }
            catch (Exception ex)
            {
                MessageBox.Show("执行查询时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                
                // 确保分页控件可用
                if (paginationControl != null)
                {
                    paginationControl.Enabled = true;
                }
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }
       
        
        /// <summary>
        /// 使用获取的数据更新UI
        /// </summary>
        private void UpdateUIWithData(ApiPaging<List<LableModel>> model)
        {
            try
            {
                // 将数据转换为DataTable
                DataTable dt = DataConverHelper.ToDataTable(model.Data);
                
                // 设置DataTable中日期时间列的格式
                if (dt.Columns.Contains("CreatedTime"))
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        if (row["CreatedTime"] != DBNull.Value && row["CreatedTime"] is DateTime)
                        {
                            // 确保DateTime值包含时分秒
                            DateTime dateTime = (DateTime)row["CreatedTime"];
                            row["CreatedTime"] = dateTime;
                        }
                    }
                }

                if (dt.Columns.Contains("UpdatedTime"))
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        if (row["UpdatedTime"] != DBNull.Value && row["UpdatedTime"] is DateTime)
                        {
                            // 确保DateTime值包含时分秒
                            DateTime dateTime = (DateTime)row["UpdatedTime"];
                            row["UpdatedTime"] = dateTime;
                        }
                    }
                }
                
                // 线程安全地更新UI
                Action updateUI = () => {
                    try
                    {
                        // 更新数据网格
                        gridControl1.DataSource = dt;
                        
                        // 更新分页控件
                        if (paginationControl != null)
                        {
                            totalRecords = model.TotalCount;
                            paginationControl.TotalRecords = totalRecords;
                            paginationControl.CurrentPage = currentPage;
                            paginationControl.PageSize = pageSize;
                            
                            // 确保分页控件可用
                            paginationControl.Enabled = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("更新UI控件时发生错误：" + ex.Message, "UI更新错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                };
                
                // 确保在UI线程上更新控件
                if (gridControl1.InvokeRequired)
                {
                    gridControl1.Invoke(updateUI);
                }
                else
                {
                    updateUI();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("更新UI数据时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                
                // 确保分页控件可用
                if (paginationControl != null)
                {
                    if (paginationControl.InvokeRequired)
                    {
                        paginationControl.Invoke(new Action(() => paginationControl.Enabled = true));
                    }
                    else
                    {
                        paginationControl.Enabled = true;
                    }
                }
            }
        }

        /// <summary>
        /// 清空
        /// </summary>
        public void Clear()
        {
            // 清空搜索框
            TxtCode.Text = "";
            TxtName.Text = "";

            // 重置分页参数
            currentPage = 1;
            if (paginationControl != null)
            {
                paginationControl.CurrentPage = 1;
            }

            // 重新加载数据
            LoadData();
        }

        /// <summary>
        /// 导出Excel的高级方法，支持自定义设置
        /// </summary>
        /// <param name="filePath">文件保存路径</param>
        /// <param name="isXlsx">是否为XLSX格式</param>
        private void ExportToExcelAdvanced(string filePath, bool isXlsx)
        {
            try
            {
                // 检查数据源是否为空
                DataTable dataSource = gridControl1.DataSource as DataTable;
                if (dataSource == null || dataSource.Rows.Count == 0)
                {
                    MessageBox.Show("没有数据可导出，请先查询数据。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (isXlsx)
                {
                    // 创建XLSX导出选项
                    XlsxExportOptionsEx options = new XlsxExportOptionsEx();

                    // 设置导出选项
                    options.ExportType = DevExpress.Export.ExportType.WYSIWYG; // 所见即所得
                    options.SheetName = "标签信息"; // 设置工作表名称
                    options.TextExportMode = TextExportMode.Value; // 导出值而不是显示文本

                    // 设置标题和页眉
                    options.ExportHyperlinks = true; // 导出超链接
                    options.ShowGridLines = true; // 显示网格线

                    // 导出到Excel
                    gridControl1.ExportToXlsx(filePath, options);
                }
                else
                {
                    // 创建XLS导出选项
                    XlsExportOptionsEx options = new XlsExportOptionsEx();

                    // 设置导出选项
                    options.ExportType = DevExpress.Export.ExportType.WYSIWYG; // 所见即所得
                    options.SheetName = "标签信息"; // 设置工作表名称
                    options.TextExportMode = TextExportMode.Value; // 导出值而不是显示文本

                    // 设置标题和页眉
                    options.ExportHyperlinks = true; // 导出超链接
                    options.ShowGridLines = true; // 显示网格线

                    // 导出到Excel
                    gridControl1.ExportToXls(filePath, options);
                }
            }
            catch (IOException ioEx)
            {
                MessageBox.Show("导出Excel时发生I/O错误：" + ioEx.Message + "\n可能是文件被占用或没有写入权限。",
                               "I/O错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出Excel时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        private async void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            try
            {
                // 检查是否点击的是 IsEnable 列
                if (e.Column.FieldName == "IsEnable")
                {
                    // 获取当前行的数据
                    int index = gridView1.FocusedRowHandle;
                    if (index < 0) return;

                    // 获取当前行的数据
                    DataRow row = gridView1.GetDataRow(index);
                    if (row == null) return;

                    // 切换 IsEnable 的值
                    bool currentValue = row["IsEnable"] != DBNull.Value && Convert.ToBoolean(row["IsEnable"]);
                    bool newValue = !currentValue;
                    row["IsEnable"] = newValue;

                    // 创建 LableModel 对象以更新数据库
                    LableModel label = new LableModel();
                    label.LId = Convert.ToInt64(row["LId"]);
                    label.IsEnable = newValue;
                    label.LalId = row["LalId"].ToString();
                    label.LabName = row["LabName"].ToString();
                    label.SupplierId= row["SupplierId"].ToString();
                    label.SupplierName = row["SupplierName"].ToString();
                    label.Delimiter = row["Delimiter"].ToString();
                    label.Format= row["Format"].ToString();
                    label.FormatMemo= row["FormatMemo"].ToString();
                    try
                    {
                        // 显示等待光标
                        Cursor = Cursors.WaitCursor;
                        // 显示确认对话框
                        var Message = string.Empty;
                        if (newValue)
                        {
                            Message = "启用";
                        }
                        else
                        {
                            Message = "停用";
                        }
                        DialogResult result = MessageBox.Show($"确定要{Message} {label.LabName}吗？",
                                                          Message + "确认",
                                                          MessageBoxButtons.YesNo,
                                                          MessageBoxIcon.Warning,
                                                          MessageBoxDefaultButton.Button2);

                        // 用户确认停用/启用
                        if (result == DialogResult.Yes)
                        {
                            // 调用API更新启用状态
                            string action = "WareHouse/Label/UpdateEnable";
                            string json = await HttpClientHelper.RequestUrl(RequestType.Put, action, JsonConvert.SerializeObject(label));
                            ApiPaging<int> model = JsonConvert.DeserializeObject<ApiPaging<int>>(json);

                            // 如果更新失败，恢复原值并显示错误信息
                            if (model.Code != ApiEnums.Success)
                            {
                                row["IsEnable"] = currentValue; // 恢复原值
                                MessageBox.Show("更新启用状态失败：" + model.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        else
                        {
                            row["IsEnable"] = currentValue; // 恢复原值
                        }
                    }
                    catch (Exception ex)
                    {
                        // 恢复原值
                        row["IsEnable"] = currentValue;
                        MessageBox.Show("更新启用状态时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        // 恢复光标
                        Cursor = Cursors.Default;

                        // 刷新显示
                        gridView1.RefreshData();
                    }
                }
                //else if (e.Column.FieldName == "删除")
                //{
                //    //DeleteWareHouse();
                //}
                //else if (e.Column.FieldName == "修改")
                //{
                //    //UpdateWareHouse();
                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show("处理启用状态时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Enable_QueryCheckStateByValue(object sender, DevExpress.XtraEditors.Controls.QueryCheckStateByValueEventArgs e)
        {
            string val = "";
            if (e.Value != null)
            {
                val = e.Value.ToString();
            }
            else
            {
                val = "False";//默认为不选   
            }
            switch (val)
            {
                case "True":
                case "Yes":
                case "1":
                    e.CheckState = CheckState.Checked;
                    break;
                case "False":
                case "No":
                case "0":
                    e.CheckState = CheckState.Unchecked;
                    break;
                default:
                    e.CheckState = CheckState.Unchecked;//初始化就是不选
                    break;
            }
            e.Handled = true;
        }

        private void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
    }
}